//
//  communityViewController.m
//  YuErmuYing
//
//  Created by Tiancheng on 16/8/8.
//  Copyright © 2016年 Tiancheng. All rights reserved.
//

#import "communityViewController.h"
#import "TCLYEvaluationViewController.h"
#import "TCLYPublishedViewController.h"
#import "Macros.h"
#import "Masonry.h"
#import "UIView+HB.h"
#import "TCLYCommunityModel.h"
#import "TCLYOrderTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "TCLYRegisterView.h"
#import "TCLYPayViewController.h"
#import "TCLYUser.h"
@interface communityViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) TCLYCommunityModel * communityModel;

@property (nonatomic, strong) UITableView * payTableView;
@property (nonatomic, strong) UITableView * deliveryTableView;
@property (nonatomic, strong) UITableView * goodsTableView;
@property (nonatomic, strong) UITableView * evaluationTableView;
@property (nonatomic, strong) UITableView * publishedTabeleView;
@property (nonatomic, strong) TCLYRegisterView * registerView;
@property (nonatomic, strong) TCLYUser * user;
@end

@implementation communityViewController

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
//    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(evaluation) name:@"evaluation" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(evaluation) name:@"published" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucceedViewCtr) name:@"paySucceedViewCtr" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createWork) name:@"loadOrderSucceed" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(babyShoppingOrderSucceed) name:@"babyShoppingOrderSucceed" object:nil];
    
    self.user = [[TCLYUser alloc] init];
    self.communityModel = [[TCLYCommunityModel alloc] init];
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId, @"uid", nil];
    [self.communityModel loadOrderParameter:dic];
    self.titleArray = @[@"待付款", @"待发货", @"待收货", @"待评价", @"待晒单"];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.registerView = [[TCLYRegisterView alloc] init];
    [self createView];
    [self createTitleView];
    

}
-(void) createWork{
    NSLog(@"收到通知");
    [self.payTableView reloadData];
    [self.deliveryTableView reloadData];
    [self.goodsTableView reloadData];
    [self.evaluationTableView reloadData];
    [self.publishedTabeleView reloadData];
}
-(void) createView{
    //可以利用循环来创建这几个TableView的
    
    UIView * payView = [[UIView alloc] init];
    payView.backgroundColor = bgColor;
    payView.frame = CGRectMake(0, 0, screenWidth, screenHeight-64-44-45);
    
    UIView * deliveryView = [[UIView alloc] init];
    deliveryView.backgroundColor = bgColor;
    deliveryView.frame = CGRectMake(0, 0, screenWidth, screenHeight-64-44-45);
    
    UIView * goodsView = [[UIView alloc] init];
    goodsView.backgroundColor = bgColor;
    goodsView.frame = CGRectMake(0, 0, screenWidth, screenHeight-64-44-45);
    
    UIView * evaluationView = [[UIView alloc] init];
    evaluationView.backgroundColor = bgColor;
    evaluationView.frame = CGRectMake(0, 0, screenWidth, screenHeight-64-44-45);
    
    UIView * publishedView = [[UIView alloc] init];
    publishedView.backgroundColor = bgColor;
    publishedView.frame = CGRectMake(0, 0, screenWidth, screenHeight-64-44-45);
    
    
    self.viewArray = @[payView,deliveryView,goodsView,evaluationView,publishedView];
    

    self.payTableView = [[UITableView alloc] init];
    self.payTableView.backgroundColor = bgColor;
    [self.payTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.payTableView.dataSource = self;
    self.payTableView.delegate = self;
    [payView addSubview:self.payTableView];
    [self.payTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(payView.mas_top);
        make.left.mas_equalTo(payView.mas_left);
        make.right.mas_equalTo(payView.mas_right);
        make.height.mas_equalTo(screenHeight-64-44-45);
    }];
    
    self.deliveryTableView = [[UITableView alloc] init];
    self.deliveryTableView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    [self.deliveryTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.deliveryTableView.dataSource = self;
    self.deliveryTableView.delegate = self;
    [deliveryView addSubview:self.deliveryTableView];
    [self.deliveryTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(deliveryView.mas_top);
        make.left.mas_equalTo(deliveryView.mas_left);
        make.right.mas_equalTo(deliveryView.mas_right);
        make.height.mas_equalTo(screenHeight-64-44-45);
    }];
    
    self.goodsTableView = [[UITableView alloc] init];
    self.goodsTableView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    [self.goodsTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.goodsTableView.dataSource = self;
    self.goodsTableView.delegate = self;
    [goodsView addSubview:self.goodsTableView];
    [self.goodsTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(goodsView.mas_top);
        make.left.mas_equalTo(goodsView.mas_left);
        make.right.mas_equalTo(goodsView.mas_right);
        make.height.mas_equalTo(screenHeight-64-44-45);
    }];
    
    self.evaluationTableView = [[UITableView alloc] init];
    self.evaluationTableView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    [self.evaluationTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.evaluationTableView.dataSource = self;
    self.evaluationTableView.delegate = self;
    [evaluationView addSubview:self.evaluationTableView];
    [self.evaluationTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(evaluationView.mas_top);
        make.left.mas_equalTo(evaluationView.mas_left);
        make.right.mas_equalTo(evaluationView.mas_right);
        make.height.mas_equalTo(screenHeight-64-44-45);
    }];
    
    self.publishedTabeleView = [[UITableView alloc] init];
    self.publishedTabeleView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
    [self.publishedTabeleView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.publishedTabeleView.dataSource = self;
    self.publishedTabeleView.delegate = self;
    [publishedView addSubview:self.publishedTabeleView];
    [self.publishedTabeleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(publishedView.mas_top);
        make.left.mas_equalTo(publishedView.mas_left);
        make.right.mas_equalTo(publishedView.mas_right);
        make.height.mas_equalTo(screenHeight-64-44-45);
    }];


}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//tableView 必须实现的两个代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.payTableView]) {
        return self.communityModel.payArr.count;
    }
    if ([tableView isEqual:self.deliveryTableView]) {
        return self.communityModel.deliveryArr.count;
    }
    if ([tableView isEqual:self.goodsTableView]) {
        return self.communityModel.goodsArr.count;
    }
    if ([tableView isEqual:self.evaluationTableView]) {
        return self.communityModel.evaluationArr.count;
    }
    if ([tableView isEqual:self.publishedTabeleView]) {
        return self.communityModel.publishedArr.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * identifier = @"orderCell";
    TCLYOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        if ([tableView isEqual:self.payTableView]) {
            cell = [[TCLYOrderTableViewCell alloc] initWithReuseIdentifier:identifier SerialNumber:1];
        }
        if ([tableView isEqual:self.deliveryTableView]) {
            cell = [[TCLYOrderTableViewCell alloc] initWithReuseIdentifier:identifier SerialNumber:2];
        }
    
        if ([tableView isEqual:self.goodsTableView]) {
            cell = [[TCLYOrderTableViewCell alloc] initWithReuseIdentifier:identifier SerialNumber:3];
        }
        if ([tableView isEqual:self.evaluationTableView]) {
            cell = [[TCLYOrderTableViewCell alloc] initWithReuseIdentifier:identifier SerialNumber:4];
        }
        if ([tableView isEqual:self.publishedTabeleView]) {
            cell = [[TCLYOrderTableViewCell alloc] initWithReuseIdentifier:identifier SerialNumber:5];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //支付
    if ([tableView isEqual:self.payTableView]) {
        NSURL * url = [NSURL URLWithString:self.communityModel.payArr[indexPath.row][@"goods_pic"]];
        [cell.goodsImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"LYJia2"]];
        cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.payArr[indexPath.row][@"sum"]];
        cell.goodsInstructionsLabel.text = self.communityModel.payArr[indexPath.row][@"goods_name"];
        cell.goodsNumLabel.text = @"X1";
        cell.goodsPriceLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.payArr[indexPath.row][@"price"]];
        cell.goodsSumLabel.text = [NSString stringWithFormat:@"共%@件商品",self.communityModel.payArr[indexPath.row][@"num"]];
        cell.payBtn.tag = 1000+indexPath.row;
        [cell.payBtn addTarget:self action:@selector(payBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    //发货
    if ([tableView isEqual:self.deliveryTableView]) {
        NSURL * url = [NSURL URLWithString:self.communityModel.deliveryArr[indexPath.row][@"goods_pic"]];
        [cell.goodsImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"jiazai"]];

        cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.deliveryArr[indexPath.row][@"sum"]];
        cell.goodsInstructionsLabel.text = self.communityModel.deliveryArr[indexPath.row][@"goods_name"];
        cell.goodsNumLabel.text = @"X1";
        cell.goodsPriceLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.deliveryArr[indexPath.row][@"price"]];
        cell.goodsSumLabel.text = [NSString stringWithFormat:@"共%@件商品",self.communityModel.deliveryArr[indexPath.row][@"num"]];
        cell.deliveryBtn.tag = 1000+indexPath.row;
        [cell.deliveryBtn addTarget:self action:@selector(deliveryBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        if ([self.communityModel.deliveryArr[indexPath.row][@"remind"] isEqual:@"1"]) {
            cell.deliveryBtn.selected = YES;
        }else{
            cell.deliveryBtn.selected = NO;
        }
        cell.cancelBtn.tag = 3000+indexPath.row;
        [cell.cancelBtn addTarget:self action:@selector(cancelBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    //收货
    if ([tableView isEqual:self.goodsTableView]) {
        NSURL * url = [NSURL URLWithString:self.communityModel.goodsArr[indexPath.row][@"goods_pic"]];
        [cell.goodsImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"jiazai"]];
        
        cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.goodsArr[indexPath.row][@"sum"]];
        cell.goodsInstructionsLabel.text = self.communityModel.goodsArr[indexPath.row][@"goods_name"];
        cell.goodsNumLabel.text = @"X1";
        cell.goodsPriceLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.goodsArr[indexPath.row][@"price"]];;
        cell.goodsSumLabel.text = [NSString stringWithFormat:@"共%@件商品",self.communityModel.goodsArr[indexPath.row][@"num"]];
        cell.goodsBtn.tag = 1000+indexPath.row;
        [cell.goodsBtn addTarget:self action:@selector(goodsBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    //评价
    if ([tableView isEqual:self.evaluationTableView]) {
        
        NSURL * url = [NSURL URLWithString:self.communityModel.evaluationArr[indexPath.row][@"goods_pic"]];
        [cell.goodsImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"LYJia2"]];
        
        cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.evaluationArr[indexPath.row][@"sum"]];
        cell.goodsInstructionsLabel.text = self.communityModel.evaluationArr[indexPath.row][@"goods_name"];
        cell.goodsNumLabel.text = @"X1";
        cell.goodsPriceLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.evaluationArr[indexPath.row][@"price"]];
        cell.goodsSumLabel.text = [NSString stringWithFormat:@"共%@件商品",self.communityModel.evaluationArr[indexPath.row][@"num"]];
        cell.evaluationBtn.tag = 1000+indexPath.row;
        [cell.evaluationBtn addTarget:self action:@selector(evaluationBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    //晒单
    if ([tableView isEqual:self.publishedTabeleView]) {
        NSURL * url = [NSURL URLWithString:self.communityModel.publishedArr[indexPath.row][@"pic"]];
        [cell.goodsImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"LYJia2"]];
        
        cell.priceLabel.text = [NSString stringWithFormat:@"￥1"];
        cell.goodsInstructionsLabel.text = self.communityModel.publishedArr[indexPath.row][@"tname"];
        cell.discountLabel.text = [NSString stringWithFormat:@"￥%@",self.communityModel.publishedArr[indexPath.row][@"sum"]];
        cell.goodsNumLabel.text = @"X1";
        cell.goodsSumLabel.text = [NSString stringWithFormat:@"共%@件商品",self.communityModel.publishedArr[indexPath.row][@"num"]];
        cell.publishedBtn.tag = 1000+indexPath.row;
        [cell.publishedBtn addTarget:self action:@selector(publishedBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 215.0;
}
//付款的按钮事件
-(void)payBtnAction:(id)sender{
    TCLYPayViewController * payViewCtr = [[TCLYPayViewController alloc] init];
    double price;
    price = [self.communityModel.payArr[((UIButton *)sender).tag-1000][@"price"] doubleValue];
    double num;
    num = [self.communityModel.payArr[((UIButton *)sender).tag-1000][@"num"] doubleValue];
    payViewCtr.payDic = @{@"sumPrice":[NSString stringWithFormat:@"%f",price*num],@"orderId":self.communityModel.payArr[((UIButton *)sender).tag-1000][@"oid"]};
    payViewCtr.isBaby = NO;
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:payViewCtr animated:YES];
}
//提醒发货的按钮事件
-(void)deliveryBtnAction:(id) sender{
    UIButton * btn = [self.view viewWithTag:((UIButton *) sender).tag];
    if (btn.selected == NO) {
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.communityModel.deliveryArr[((UIButton *) sender).tag-1000][@"oid"],@"oid", nil];
        [self.communityModel deliveryParameter:dic];
        NSLog(@"%ld",(long)((UIButton *) sender).tag);
        btn.selected = YES;
    }else{
        [self.registerView prompt:@"已经提醒过发货哦！" Controller:self];
    }
}
//取消订单的按钮事件
-(void)cancelBtnAction:(id)sender{
    [self.registerView Prompt:@"确定要取消订单吗?" Controller:self];
    self.registerView.determineAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//        NSDate *datenow =[NSDate date];//现在时间,你可以输出来看下是什么格式
//        NSTimeZone *zone = [NSTimeZone systemTimeZone];
//        NSInteger interval = [zone secondsFromGMTForDate:datenow];
//        NSDate *localeDate = [datenow  dateByAddingTimeInterval: interval];
//        NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[localeDate timeIntervalSince1970]];
//        NSLog(@"当前的时间戳%@",timeSp);
//        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
//        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//        NSString * dataTime = [formatter stringFromDate:datenow];
//        NSLog(@"当前的时间%@",dataTime);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelParameter) name:@"cancelOrderSucced" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelAction) name:@"cancelOrderError" object:nil];
        NSLog(@"Oid:%@",self.communityModel.deliveryArr[((UIButton *) sender).tag - 3000][@"oid"]);
        //封装请求参数
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId,@"uid",self.communityModel.deliveryArr[((UIButton *)sender).tag-3000][@"oid"],@"oid", nil];
        
        [self.communityModel cancelParameter:dic];
        [self.registerView.promptAlertCtr dismissViewControllerAnimated:YES completion:nil];
        
        return ;
    }];
    self.registerView.cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.registerView.promptAlertCtr dismissViewControllerAnimated:YES completion:nil];
        return ;
    }];
    [self.registerView.promptAlertCtr addAction:self.registerView.determineAction];
    [self.registerView.promptAlertCtr addAction:self.registerView.cancelAction];
    
}
//确认收货的按钮事件
-(void)goodsBtnAction:(id)sender{
    [self.registerView Prompt:@"确定要收货吗?" Controller:self];
    self.registerView.determineAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goodsParameter) name:@"goodsOrder" object:nil];
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.communityModel.goodsArr[((UIButton *) sender).tag - 1000][@"oid"],@"oid", self.user.userId, @"uid",nil];
        [self.communityModel goodsParameter:dic];
        
        [self.registerView.promptAlertCtr dismissViewControllerAnimated:YES completion:nil];
    }];
    self.registerView.cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.registerView.promptAlertCtr dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.registerView.promptAlertCtr addAction:self.registerView.determineAction];
    [self.registerView.promptAlertCtr addAction:self.registerView.cancelAction];
}
//评价的按钮事件
-(void)evaluationBtnAction:(id)sender{
    TCLYEvaluationViewController * evaluationViewCtr = [[TCLYEvaluationViewController alloc] init];
    evaluationViewCtr.evaluationDic = self.communityModel.evaluationArr[((UIButton *)sender).tag-1000];
    [self.navigationController pushViewController:evaluationViewCtr animated:NO];
}
//晒单的按钮事件
-(void)publishedBtnAction:(id)sender{
    TCLYPublishedViewController * publishedViewCtr = [[TCLYPublishedViewController alloc] init];
    
    publishedViewCtr.publishedDic = self.communityModel.publishedArr[((UIButton *) sender).tag - 1000];
    [self.navigationController pushViewController:publishedViewCtr animated:NO];
}
//取消后的数据刷新
-(void)cancelParameter{
    [self.deliveryTableView reloadData];
}
-(void)evaluation{
    
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId, @"uid", nil];
    
    [self.communityModel loadOrderParameter:dic];
    
}
//取消后数据刷新失败（超过时间）
-(void)cancelAction{
    [self.registerView prompt:@"您已超过取消订单的时间" Controller:self];
    
}
-(void)goodsParameter{
    [self.goodsTableView reloadData];
}
-(void)createTitleView{
    self.navigationController.navigationBar.barStyle = UIBarMetricsCompactPrompt;
    self.navigationController.navigationBar.backgroundColor = statusColor;
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, -20, screenWidth, 20)];
    view.backgroundColor = navColor;
    [self.navigationController.navigationBar addSubview:view];
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"订单";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.frame = CGRectMake(0, 0, 50, 20);
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = titleLabel;
}
-(void)babyShoppingOrderSucceed{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createWork) name:@"loadOrderSucceed" object:nil];
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId, @"uid", nil];
    [self.communityModel loadOrderParameter:dic];

}

-(void)paySucceedViewCtr{
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:self.user.userId, @"uid", nil];
    [self.communityModel loadOrderParameter:dic];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
